const express = require('express');
const cors = require('cors');
// 使用 Node.js 原生 fetch (Node.js 18+)

const app = express();
const PORT = process.env.PORT || 3000;
const GOOGLE_URL = "https://oauth2.googleapis.com";

// 启用 CORS
app.use(cors());

// 解析 JSON 请求体
app.use(express.json());
// 解析 application/x-www-form-urlencoded（Google OAuth token 接口常用）
app.use(express.urlencoded({ extended: false }));

// 代理所有请求到 Google OAuth API
app.all('*', async (req, res) => {
  try {
    // 构建目标 URL
    const proxy_url = `${GOOGLE_URL}${req.originalUrl}`;

    // 设置请求头
    const outboundHeaders = { ...req.headers };
    
    // 删除可能导致问题的头部
    delete outboundHeaders['host'];
    delete outboundHeaders['connection'];
    delete outboundHeaders['content-length'];
    delete outboundHeaders['accept'];
    delete outboundHeaders['accept-encoding'];

    // 根据 Content-Type 正确编码请求体
    const contentType = (outboundHeaders['content-type'] || '').toLowerCase();
    let outboundBody;
    if (req.method !== 'GET' && req.method !== 'HEAD') {
      if (contentType.includes('application/x-www-form-urlencoded')) {
        // 重新编码为 x-www-form-urlencoded 字符串
        outboundBody = new URLSearchParams(req.body).toString();
        outboundHeaders['content-type'] = 'application/x-www-form-urlencoded';
      } else if (contentType.includes('application/json')) {
        outboundBody = JSON.stringify(req.body);
        outboundHeaders['content-type'] = 'application/json';
      } else if (contentType.includes('text/plain')) {
        outboundBody = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
        outboundHeaders['content-type'] = 'text/plain';
      } else {
        // 其它类型（例如 multipart/form-data）由于已被 bodyParser 消费，这里无法无损转发
        // 可按需扩展：改用原始流转发或移除 bodyParser
        outboundBody = undefined;
      }
    }

    // 发送请求到 Google API
    const response = await fetch(proxy_url, {
      method: req.method,
      headers: outboundHeaders,
      body: outboundBody,
    });


    if (response.status === 404){
      // 返回 404 隐藏 google 页面
      res.status(404);  
      res.send('Not Found');
      return
    }
    
    // 获取响应数据为二进制，避免编码/压缩不一致导致 incorrect header check
    const responseArrayBuffer = await response.arrayBuffer();
    const responseBuffer = Buffer.from(responseArrayBuffer);

    // 设置响应头
    const responseHeaders = {};
    response.headers.forEach((value, key) => {
      responseHeaders[key] = value;
    });
    
    // 清理与压缩相关、长度相关的头，防止客户端重复解压或长度不符
    delete responseHeaders['content-encoding'];
    delete responseHeaders['transfer-encoding'];
    delete responseHeaders['content-length'];

    // 发送响应
    res.set(responseHeaders);
    res.status(response.status).send(responseBuffer);
    
  } catch (error) {
    console.error('代理请求错误:', error);
    res.status(500).json({ error: '代理请求失败' });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Google OAuth 代理服务器运行在端口 ${PORT}`);
  console.log(`代理目标: ${GOOGLE_URL}`);
});
